package groupon.com.service;

import groupon.user.bo.service.AccountService;
import groupon.user.model.Account;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class CustomUserDetailsService implements UserDetailsService{

	private final static Log logger = LogFactory.getLog(CustomUserDetailsService.class);
	
	@Autowired
	private AccountService _accountService;
	
	//get userdetail and get role
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		UserDetails user = null;
		Account account = _accountService.findAccountByUsername(username);
		/*Account account = new Account();
		account.setUsername("admin");
		account.setPassword("21232f297a57a5a743894a0e4a801fc3");
		account.setRole("BO");*/
		if(account != null){
			user = new User(account.getUsername(), account.getPassword().toLowerCase(), true, true, true, true, getAuthorities(account.getRole()));
		}
		// TODO Auto-generated method stub
		return user;
	}
	
	
	/**
	 * Retrieves the correct ROLE type depending on the access level, where access level is an Integer.
	 * Basically, this interprets the access value whether it's for a regular user or admin.
	 * 
	 * @param access an integer value representing the access of the user
	 * @return collection of granted authorities
	 */
	//check role
	 public Collection<GrantedAuthority> getAuthorities(String role) {
			// Create a list of grants for this user
			List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
			
			// All users are granted with ROLE_USER access
			// Therefore this user gets a ROLE_USER by default
			logger.debug("Grant ROLE_USER to this user");
			authList.add(new GrantedAuthorityImpl("ROLE_USER"));
			
			// Check if this user has admin access 
			// We interpret Integer(BO) as an admin user
			if ( role.compareTo("BO") == 0) {
				// User has admin access
				logger.debug("Grant ROLE_ADMIN to this user");
				authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
			}
			// Return list of granted authorities
			return authList;
	  }

}
